package com.example.treasure_back.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.treasure_back.entity.ChatroomEntity;
import com.example.treasure_back.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint(value = "/chatroom/{userId}/{id}")
public class ChatroomWebSocket {

    public static int onlineNumber = 0;
    private static Map<String, ChatroomWebSocket> clients = new ConcurrentHashMap<>();
    private Session session;
    private String userId;
    private String id;
    private static UserService userService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    public void setUserService(UserService userService){
        ChatroomWebSocket.userService=userService;
    }
    //建立连接
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session, @PathParam("id") String id)
    {
        onlineNumber++;
        this.userId = userId;
        this.session = session;
        this.id = id;
        // 插入用户
        ChatroomEntity.addUser(id, userId);
        // 将新连接的用户加入列表中
        clients.put(userId, this);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    //连接关闭
    @OnClose
    public void onClose()
    {
        onlineNumber--;
        clients.remove(userId);
        ChatroomEntity.removeUser(id,userId);
        System.out.println("有连接关闭！ 当前在线人数" + clients.size());
    }
    //收到客户端的消息
    @OnMessage
    public void onMessage(String message, Session session)
    {
        String avatar = userService.getAvatar(userId);
        String username = userService.getUsername(userId);
        try {
            JSONObject jsonObject = JSON.parseObject(message);
            jsonObject.put("userId", userId);
            jsonObject.put("avatar", avatar);
            jsonObject.put("username", username);
            String msg = jsonObject.toJSONString();
            sendMessageAll(msg, userId);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    public void sendMessageAll(String message,String FromuserId) throws IOException {
        // 遍历每一个在线用户，发送消息
        List<String> range = new ArrayList<>(ChatroomEntity.getUsers(id));
        range.remove(userId);
        for (String s : range) {
            ChatroomWebSocket chatroomWebSocket = clients.get(s);
            chatroomWebSocket.session.getAsyncRemote().sendText(message);
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineNumber;
    }


}
